import csv
import random

words_dict = []
words_list = []
unit_list = []
unit_word_len_dict = {}
words_length = 0
order_type = 0

star_words_dict = {}
star_words_tuples = []


def init_unit_list():
    global words_length
    unit_list.clear()
    unit_word_len_dict.clear()
    words_list.clear()
    words_length = 0
    init_star_words()
    with open('words_dict/dict.csv')as f:
        f_csv = csv.reader(f)
        for row in f_csv:
            words_list.append(row)
            unit_list.append(row[0])
            unit_word_len_dict[row[0]] = len(row) - 1
            words_length += len(row) - 1


def init_star_words():
    star_words_tuples.clear()
    star_words_dict.clear()
    with open('words_dict/star_words.csv')as f:
        f_csv = csv.reader(f)
        for row in f_csv:
            star_index = len(star_words_tuples)
            star_words_dict[row[0]] = star_index
            word_tuple = [row[0], row[1]]
            star_words_tuples.append(word_tuple)


def write_star_csv():
    with open('words_dict/star_words.csv', 'w', newline='')as f:
        f.truncate()
        f_writer = csv.writer(f)
        f_writer.writerows(star_words_tuples)


def add_star_word(word, unit):
    star_words_dict[word] = len(star_words_tuples)
    word_tuple = [word, unit]
    star_words_tuples.append(word_tuple)
    write_star_csv()


def cancel_star_word(word):
    if not star_words_dict.__contains__(word):
        return
    star_index = int(star_words_dict.pop(word))
    del star_words_tuples[star_index]
    write_star_csv()


def no_need_2_load(unit, selected_unit_name):
    return unit != selected_unit_name


# 载入章节
def init_dict(range_type, selected_unit, dict_order_type):
    global words_length
    global order_type
    order_type = dict_order_type
    words_length = 0
    words_dict.clear()
    index_cursor = 0
    init_star_words()
    with open('words_dict/dict.csv')as f:
        f_csv = csv.reader(f)
        for row in f_csv:
            unit = row[0]
            if range_type == '2':
                if index_cursor > len(selected_unit) - 1:
                    break
                if no_need_2_load(unit, unit_list[int(selected_unit[index_cursor])]):
                    continue
            index_cursor += 1
            for idx in range(1, len(row)):
                this_word = [unit, row[idx]]
                words_dict.append(this_word)
        words_length = len(words_dict)


'''
包装响应
'''


def wrap_response(idx, word_tuple):
    is_star = "0"
    if star_words_dict.__contains__(word_tuple[1]):
        is_star = "1"
    return {'index': idx, 'unit': word_tuple[0], 'word': word_tuple[1], 'is_star': is_star, 'remain': words_length - 1}


'''
生成索引
'''


def generate_unit_tuple():
    unit_tuples = []
    idx = 0
    for unit in unit_list:
        unit_tuple = [idx, unit, unit_word_len_dict[unit]]
        unit_tuples.append(unit_tuple)
        idx += 1
    return unit_tuples


# 顺序模式索引
def generate_seq_idx(index):
    if index >= words_length - 1:
        return 0
    return index + 1


# 随机模式索引
def generate_random_idx(begin, end):
    return random.randint(begin, end)


# 移除单词
def remove_word(index):
    global words_length
    del words_dict[index]
    words_length -= 1


def fetch_word(idx, op_type):
    index = int(idx)
    # 如果是记住了, 就在内存删掉当前单词
    if op_type == '2':
        remove_word(index)
        index -= 1
        if words_length <= 0:
            return {}
    # 如果是随机模式, 就随机获取idx
    if order_type == '2':
        index = generate_random_idx(0, words_length - 1)
    # 顺序模式, idx加一
    else:
        index = generate_seq_idx(index)
    word_tuple = words_dict[index]
    return wrap_response(index, word_tuple)


def fetch_unit_words(index):
    unit_name = unit_list[int(index)]
    unit_words = []
    for words in words_list:
        if words[0] != unit_name:
            continue
        unit_words = words[1:]
        break
    words_tuple = []
    for word in unit_words:
        cur_tuple = [word]
        if star_words_dict.__contains__(word):
            cur_tuple.append("1")
        else:
            cur_tuple.append("0")
        words_tuple.append(cur_tuple)
    return unit_name, words_tuple


def add_words(unit_name, word_list):
    if words_length == 0 or len(words_list) == 0:
        init_unit_list()
    flag = False
    for row in words_list:
        if row[0] != unit_name:
            continue
        for word in word_list:
            row.append(word)
        flag = True
    if not flag:
        word_list.insert(0, unit_name)
        words_list.append(word_list)
    save_csv()


def save_csv():
    with open('words_dict/dict.csv', 'w', newline='')as f:
        f.truncate()
        f_writer = csv.writer(f)
        f_writer.writerows(words_list)
    init_unit_list()


def cascade_delete(unit_name, index):
    split_index = index.split(",")
    deleted_count = 0
    deleted_star_count = 0
    for words in words_list:
        if words[0] != unit_name:
            continue
        for idx in split_index:
            # 删除单词表
            int_idx = int(idx) + 1 - deleted_count
            word = words[int_idx]
            del words[int_idx]
            deleted_count += 1
            # 删除收藏单词映射
            if not star_words_dict.__contains__(word):
                continue
            star_idx = int(star_words_dict.pop(word)) - deleted_star_count
            # 删除收藏单词表
            del star_words_tuples[star_idx]
            deleted_star_count += 1
        break
    # 保存收藏单词表
    write_star_csv()
    # 保存单词表
    save_csv()
